package com.acol.estagio.workflow.struts.action;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.acol.estagio.workflow.dao.JogosDAO;
import com.acol.estagio.workflow.services.util.EstagioServices;
import com.acol.estagio.workflow.struts.form.GerenciarTimesForm;
import com.acol.estagio.workflow.vo.ContaVO;
import com.acol.estagio.workflow.vo.JogosVO;
import com.acol.estagio.workflow.vo.TimesVO;

public class GerenciarTimesAction extends DispatchAction{
	TimesVO timesVO = new TimesVO();
	ContaVO contaVO = new ContaVO();
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm) form;
		frm.inicializar(mapping, request);
		ActionErrors errors = new ActionErrors();
		return listarTimes(mapping, form, request, response);
	}
	
	public ActionForward cadastrarTime(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm) form;
		frm.inicializar(mapping, request);
		
		return mapping.findForward("cadastrarTime");
	}
	
	public ActionForward paginaBuscarTimes (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		ActionErrors errors = new ActionErrors();
        
		Collection listaTimes = new ArrayList();
		try{
			if("".equals(frm.getTimesVO().getNomeTime())|| frm.getTimesVO().getNomeTime() == null || "paraExclusao".equals(frm.getEdicao())){
//				ContaVO contaVO = (ContaVO) request.getSession().getAttribute("contaVO");
//				Integer seqConta = contaVO.getSeqConta();
				listaTimes = EstagioServices.getCampeonatoBean().getListaTimes();
				frm.setListaTimes(listaTimes);
				frm.setBusca("sim");
				 
			}else{				
				String nomeTime = frm.getTimesVO().getNomeTime();
	
				listaTimes = EstagioServices.getCampeonatoBean().getListaTimesByNome(nomeTime);
				frm.setBusca("sim");
				if(!(listaTimes.isEmpty())){
					frm.setListaTimes(listaTimes);
					return mapping.findForward("listarTime");				
				}else{
					errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("vazia.lista.time"));
					saveErrors(request, errors);
					frm.setListaTimes(listaTimes);
					return mapping.findForward("listarTime");	
				}
			}	
		}catch(Exception e){
			errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("Erro ao tentar puchar a lista de times"));
			saveErrors(request, errors);	
		}
		return mapping.findForward("listarTime");
	}
	
	public ActionForward listarTimes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		ActionErrors errors = new ActionErrors();
        
		Collection listaTimes = new ArrayList();
		try{
			if("".equals(frm.getTimesVO().getNomeTime())|| frm.getTimesVO().getNomeTime() == null || "paraExclusao".equals(frm.getEdicao())){
				ContaVO contaVO = (ContaVO) request.getSession().getAttribute("contaVO");
				Integer seqConta = contaVO.getSeqConta();
				listaTimes = EstagioServices.getCampeonatoBean().getListaTimesByCadastro(seqConta);
			
				frm.setBusca("sim");
				
			}
			else{
				ContaVO contaVO = (ContaVO) request.getSession().getAttribute("contaVO");
				Integer seqConta = contaVO.getSeqConta();
				
				String nomeTime = frm.getTimesVO().getNomeTime();

				listaTimes = EstagioServices.getCampeonatoBean().getListaTimesByNomeCadastro(nomeTime, seqConta);
				frm.setBusca("sim");
			}

			if(!(listaTimes.isEmpty())){
				frm.setListaTimes(listaTimes);
				return mapping.findForward("manutencaoTime");
				
			}else{
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("vazia.lista.time"));
				saveErrors(request, errors);
				frm.setListaTimes(listaTimes);
			}
			return mapping.findForward("manutencaoTime");
		}catch(Exception e){
			errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("Erro ao tentar puchar a lista de times"));
			saveErrors(request, errors);
			
		}

		if(contaVO.getLogado() == 0){
			return mapping.findForward("manutencaoTime");
		}else{
			return mapping.findForward("manutencaoTime");
		}
		
	}
	public ActionForward listarTodosOsTimes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		ActionErrors errors = new ActionErrors();
		frm.inicializar(mapping, request);
		Collection listaTimes = new ArrayList();
		listaTimes = EstagioServices.getCampeonatoBean().getListaTimes();
		if(!(listaTimes.isEmpty())){
			frm.setListaTimes(listaTimes);
			return mapping.findForward("listarTime");

		}else{
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("vazia.lista.time"));
			saveErrors(request, errors);
			frm.setListaTimes(new ArrayList());
		}
		ContaVO contaVO = (ContaVO) request.getSession().getAttribute("contaVO");
		frm.setContaVO(contaVO);
		return mapping.findForward("listarTimes");
	}
	
	public ActionForward paginaDescricaoTime(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		Integer seqTime = frm.getSeqTime();
		TimesVO timesVO = EstagioServices.getCampeonatoBean().getTime(seqTime);
		frm.setTimesVO(timesVO);
		Integer seqConta = frm.getTimesVO().getSeqConta();
		ContaVO contaVO = EstagioServices.getCampeonatoBean().getConta(seqConta);
		frm.setContaVO(contaVO);
		frm.setLogoOperadoraRelatorio(timesVO.getEmblema());
		
		return mapping.findForward("descricaoTime");
	}
	
	public ActionForward inserirTime(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		
	ActionErrors errors = frm.validate(mapping, request);
		

	if(errors.isEmpty()){
			ContaVO contaVO = (ContaVO) request.getSession().getAttribute("contaVO");
			timesVO.setSeqConta(contaVO.getSeqConta());
			timesVO.setNomeTime(frm.getTimesVO().getNomeTime());
//			timesVO.setAnoCriacao(frm.getTimesVO().getAnoCriacao());
			timesVO.setSede(frm.getSede() + "  ,  " + frm.getSedeLocalizacao());
			timesVO.setEstadio(frm.getEstadio() + "  ,  " + frm.getEstadioLocalizacao());
			if(frm.getCondicao()==null){
				timesVO.setEmblema((byte[])frm.getImgOperadora().getFileData());
			}
			Collection listaTimeExiste = EstagioServices.getCampeonatoBean().getListaTimesByNomeCadastro(timesVO.getNomeTime(), contaVO.getSeqConta());
			if(listaTimeExiste.isEmpty()){
				EstagioServices.getCampeonatoBean().inserirTime(timesVO);
				errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("sucesso.times.inserir", request.getContextPath() + "/images/icon_sucesso.gif", timesVO.getNomeTime()));
				saveErrors(request, errors);
			}else{
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionError("errors.time.existente", request.getContextPath() + "/images/icon_atencao.gif"));
				saveErrors(request, errors);
			}
//			EstagioServices.getCampeonatoBean().inserirTime(timesVO);
			frm.inicializar(mapping, request);
			
			return listarTimes(mapping, form, request, response);

	   }else{
		   	errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionError("errors.campo.obrigatorio", request.getContextPath() + "/images/icon_atencao.gif"));
			saveErrors(request, errors);
			return mapping.findForward("cadastrarTime");

		}

	}
	
	public ActionForward selecionarTimeExcluir(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		TimesVO timesVO =  new TimesVO();
		Integer seqTimes = new Integer(request.getParameter("seqTime"));
		timesVO = EstagioServices.getCampeonatoBean().getTimeExcluir(seqTimes);
		frm.getTimesVO().setNomeTime(timesVO.getNomeTime());
		
			frm.setStatus("EXCLUIR");
			frm.setEdicao("paraExclusao");
			return listarTimes(mapping, form, request, response);
		
	}

	public ActionForward selecionarTime(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		TimesVO timesVO = new TimesVO();
		Integer seqTime = new Integer(request.getParameter("seqTime"));

		timesVO = EstagioServices.getCampeonatoBean().getTime(seqTime);
		frm.getTimesVO().setNomeTime(timesVO.getNomeTime());
//		frm.getTimesVO().getSede().getChars(0, frm.getTimesVO().getSede().length(), char[] sede, 0);
//		char[] sede = frm.getTimesVO().getSede().toCharArray();
		String[] sede = timesVO.getSede().split("  ,  ");
		String[] estadio = timesVO.getEstadio().split("  ,  ");
		if(timesVO.getEmblema()!=null){
			frm.setLogoOperadoraRelatorio(timesVO.getEmblema());
		}
		
//		for(int i=0; sede.length; i++){
//			
//		}
		frm.setSede(sede[0]);
		frm.setSedeLocalizacao(sede[1]);
		frm.setSeqTime(seqTime);
		frm.setEstadio(estadio[0]);
		frm.setEstadioLocalizacao(estadio[1]);
		
		return mapping.findForward("editarTime");

	}
	public ActionForward atualizarTime(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		TimesVO timesVO = new TimesVO();
		ActionErrors errors = frm.validate(mapping, request);

		if(errors.isEmpty()){

			timesVO.setNomeTime(frm.getTimesVO().getNomeTime());
//			timesVO.setAnoCriacao(frm.getTimesVO().getAnoCriacao());
			timesVO.setSede(frm.getSede() + "  ,  " + frm.getSedeLocalizacao());
			timesVO.setEstadio(frm.getEstadio() + "  ,  " + frm.getEstadioLocalizacao());
			if("".equals(frm.getImgOperadora().getFileName())){
			timesVO.setEmblema(frm.getLogoOperadoraRelatorio());
			}else{
				timesVO.setEmblema(frm.getImgOperadora().getFileData());
			}
			timesVO.setSeqTime(frm.getSeqTime());

			EstagioServices.getCampeonatoBean().alterarTimeCrieUmMetodoPraVoce(timesVO);

			frm.inicializar(mapping, request);
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("sucesso.times.alterar", request.getContextPath() + "/images/icon_sucesso.gif"));
			saveErrors(request, errors);
			return unspecified(mapping, form, request, response);

		}else{
			
			
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.campo.obrigatorio", request.getContextPath() + "/images/icon_atencao.gif"));
			saveErrors(request, errors);
			
			return mapping.findForward("editarTime");
			}
		
		
	}
	public ActionForward deleteTimes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		ActionErrors errors = new ActionErrors();
		Integer seqTime = frm.getSeqTime();
		TimesVO timeVO = new TimesVO();
//		Integer seqConta = frm.getContaVO().getSeqConta();
		Collection listaJogos = EstagioServices.getCampeonatoBean().getJogoByTime(seqTime);
//		Collection listaCampeonato = EstagioServices.getCampeonatoBean().getCampeonatosByCadastro(seqConta);
				
		//Collection listaJogos = EstagioServices.getCampeonatoBean().getListaJogos();
		timeVO = EstagioServices.getCampeonatoBean().getTime(seqTime);
		
		if(!(listaJogos.isEmpty())){
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.delete.time", request.getContextPath() + "/images/icon_atencao.gif"));
			saveErrors(request, errors);
		}else{
			EstagioServices.getCampeonatoBean().excluirTime(seqTime);
			errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("sucesso.times.deletar", request.getContextPath() + "/images/icon_sucesso.gif", "deletado"));
			saveErrors(request, errors);
			frm.inicializar(mapping, request);
		}
		return listarTimes(mapping, form, request, response);
	}
	/*public ActionForward listarTimes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		Collection listaTimes = EstagioServices.getCampeonatoBean().getListaTimes();
		frm.setListaTimes(listaTimes);
		
		return mapping.findForward("");
	}*/
	
	/**
	 * Imprimindo a imagem no jsp
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward cadastrarImagemOperadora(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		byte[] imagem = frm.getLogoOperadoraRelatorio();
		if(frm.getImgOperadora()!=null){
			timesVO.setEmblema(frm.getImgOperadora().getFileData());
			frm.setCondicao("visualizar");
		}
		if(imagem!=null) {
			response.setContentType("image/gif");
			OutputStream os = response.getOutputStream();
			os.write(imagem);
			os.flush();
			os.close();
		}
		
		return null;
	}
	public ActionForward alterarImagemOperadora(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		 byte[] imagem = frm.getLogoOperadoraRelatorio();
		if(imagem!=null) {
			response.setContentType("image/gif");
			OutputStream os = response.getOutputStream();
			os.write(imagem);
			os.flush();
			os.close();
		}

		return null;
	}

	public ActionForward alterarArquivoOperadora(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		frm.setCondicao("visualizar");
		timesVO.setEmblema((byte[])frm.getImgOperadora().getFileData());
		if(frm.getImgOperadora() !=null){
			try{
				frm.setLogoOperadoraRelatorio(frm.getImgOperadora().getFileData());
			}catch (FileNotFoundException e) {
				// TODO: handle exception
			}catch (IOException e) {
				// TODO: handle exception
			}catch (Exception e) {
				// TODO: handle exception
			}	
		}
		return mapping.findForward("cadastrarTime");
	}
	public ActionForward imagem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciarTimesForm frm = (GerenciarTimesForm)form;
		request.getSession().removeAttribute("imgOperadora");
		request.setAttribute("flgUploadSucesso", "true");
		
		if(frm.getImgOperadora() !=null){
			try{
				request.getSession().setAttribute("imgOperadora", frm.getImgOperadora().getFileData());
				frm.setLogoOperadoraRelatorio(frm.getImgOperadora().getFileData());
			}catch (FileNotFoundException e) {
				// TODO: handle exception
			}catch (IOException e) {
				// TODO: handle exception
			}catch (Exception e) {
				// TODO: handle exception
			}	
		}
		
		return mapping.findForward("editarTime");
	}
	public ActionForward postBack(ActionMapping mapping, ActionForm frm, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.findForward(request.getParameter("forward"));
	}	

}
